package valid

import (
	"github.com/go-playground/locales/zh"
	ut "github.com/go-playground/universal-translator"
	"github.com/go-playground/validator/v10"
	zh_translations "github.com/go-playground/validator/v10/translations/zh"
	"reflect"
	"vueBasic/extend/captcha"
)

var (
	Validate *validator.Validate
	Trans    ut.Translator
)

func InitValidator() *validator.Validate {
	Validate = validator.New()
	Validate.RegisterTagNameFunc(func(field reflect.StructField) string {
		name := field.Tag.Get("label")
		return name
	})
	zh := zh.New()
	uni := ut.New(zh)
	Trans, _ = uni.GetTranslator("zh")
	zh_translations.RegisterDefaultTranslations(Validate, Trans)

	//图片验证码验证
	Validate.RegisterValidation("captcha", captchaValidion)
	Validate.RegisterTranslation("captcha", Trans, translateCaptchaFunc, translateCaptchaFuncFallback)

	return Validate
}

// 验证码验证
func captchaValidion(fl validator.FieldLevel) bool {
	return captcha.Verify(fl.Parent().FieldByName("CaptchaId").String(), fl.Field().String())
}

func translateCaptchaFunc(ut ut.Translator) error {
	return ut.Add("captcha", "验证码输入错误!", true)
}

func translateCaptchaFuncFallback(ut ut.Translator, fe validator.FieldError) string {
	t, _ := ut.T("captcha", fe.Field())
	return t
}
